#include <glib.h>
#include <gio/gio.h>

static GIOChannel *channel;

static gboolean read_cb(GIOChannel *source, GIOCondition condition, gpointer data) {
    gchar *line = NULL;
    gsize length = 0;
    GError *error = NULL;

    if (g_io_channel_read_line(source, &line, &length, NULL, &error) == G_IO_ERROR_NONE) {
        g_print("Received: %s", line);
        g_free(line);
    } else {
        g_printerr("Error reading from server: %s
", error->message);
        g_error_free(error);
        return FALSE;
    }

    return TRUE;
}

static void send_message(const gchar *message) {
    GError *error = NULL;
    gsize length = strlen(message);

    if (g_io_channel_write_chars(channel, message, length, NULL, &error) == G_IO_ERROR_NONE) {
        g_print("Sent: %s", message);
    } else {
        g_printerr("Error sending message: %s
", error->message);
        g_error_free(error);
    }
}

int main(int argc, char **argv) {
    GSocketClient *client;
    GSocketConnection *connection;
    GTlsClientConnection *tls_connection;
    GError *error = NULL;
    gchar *line = NULL;
    gsize length = 0;

    g_type_init();

    client = g_socket_client_new();
    g_socket_client_set_tls(client, TRUE);
    g_socket_client_set_tls_validation_flags(client, G_TLS_CERTIFICATE_VALIDATE_ALL);
    connection = g_socket_client_connect_to_host(client, "irc.freenode.net", 6697, NULL, &error);

    if (error != NULL) {
        g_printerr("Error connecting to server: %s
", error->message);
        g_error_free(error);
        return 1;
    }

    tls_connection = g_tls_connection_get_base_io_stream(G_TLS_CONNECTION(connection));
    channel = g_io_channel_unix_new(g_socket_connection_get_fd(G_SOCKET_CONNECTION(tls_connection)));
    g_io_channel_set_close_on_unref(channel, TRUE);
    g_io_channel_ref(channel);
    g_io_add_watch(channel, G_IO_IN, read_cb, NULL);

    send_message("NICK mynick\r
");
    send_message("USER myuser 0 * :My User\r
");

    GMainLoop *loop = g_main_loop_new(NULL, FALSE);
    g_main_loop_run(loop);

    g_io_channel_unref(channel);
    g_object_unref(tls_connection);
    g_object_unref(connection);
    g_object_unref(client);

    return 0;
}

